package initialize

import (
	"os"
	"server/global"
	"server/model"


	"go.uber.org/zap"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// pg 数据库连接初始化并测试连接情况
func Gorm() *gorm.DB {
	switch global.GVA_CONFIG.System.DbType {
	case "postgresql":
		return GormPg()
	default:
		return GormPg()
	}
}
// MysqlTables 注册数据库表专用
func MysqlTables(db *gorm.DB){
	err := db.AutoMigrate(
		//model.CasbinModel{},
		model.SysAuthority{},
		)
	if err != nil {
		global.GVA_LOG.Error("register table failed", zap.Any("err", err))
		os.Exit(0)
	}
	global.GVA_LOG.Info("register table success")
}

func GormPg() *gorm.DB{
	m := global.GVA_CONFIG.Pg
	dsn := "user=" + m.Username + " password=" + m.Password + " host=" + m.Host + " port=" +m.Port + " dbname="+m.Dbname+" sslmode=" +m.Sslmode
	pgConfig := postgres.Config{
		DSN:                       dsn,   // DSN data source name
		PreferSimpleProtocol: 		true,
	}
	if db, err := gorm.Open(postgres.New(pgConfig), gormConfig(m.LogMode)); err != nil {
		global.GVA_LOG.Error("pg连接异常", zap.Any("err", err))
		os.Exit(0)
		return nil
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(m.MaxIdleConns)
		sqlDB.SetMaxOpenConns(m.MaxOpenConns)
		return db
	}
}

func gormConfig(mod bool) *gorm.Config {
	if global.GVA_CONFIG.Pg.LogZap {
		return &gorm.Config{
			Logger:  								  Default.LogMode(logger.Info),
			DisableForeignKeyConstraintWhenMigrating: true,
		}
	}
	if mod {
		return &gorm.Config{
			Logger:                                   logger.Default.LogMode(logger.Info),
			DisableForeignKeyConstraintWhenMigrating: true,
		}
	} else {
		return &gorm.Config{
			Logger:                                   logger.Default.LogMode(logger.Silent),
			DisableForeignKeyConstraintWhenMigrating: true,
		}
	}
}
